from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms

import forms

import datamodel

class Process(webapp.RequestHandler):
    def post(self):
        
        if self.request.get('nsfn') == 'addcourse':
            self.addCourse()
        elif self.request.get('nsfn') == 'adddept':
            self.addDept()
        elif self.request.get('nsfn') == 'wallpost':
            self.wallPost()
        else:
            school = datamodel.School(schName=self.request.get('name'), 
                          schAbbr=self.request.get('abbr'), 
                          webUrl=self.request.get('weburl'),
                          emailSfx=self.request.get('emailsfx'))

            school.put()
            if(self.request.get('redirect')):
                self.redirect(self.request.get('redirect'))
            else:
                self.redirect('/')
        
    def addDept(self):
        school = db.get(db.Key(self.request.get('sch')))
        
        dept = datamodel.Department(school=school,
                                dName=self.request.get('dname'),
                                dAbbr=self.request.get('dabbr'))
        dept.put()
            
        self.redirect('/')
        
    def addCourse(self):        
        data = forms.AddCourse(data=self.request.POST)
        if data.is_valid():
            dept = db.get(db.Key(self.request.get('dept')))
            
            course = data.save(commit=False)
            course.dept = dept

            course.put()
        else:
            self.response.out.write(memcache.get("form"))
        self.forward()
            
    def forward(self):
        if(self.request.get('redirect')):
            self.redirect(self.request.get('redirect'))
        else:
            self.redirect('/')
    def wallPost(self):
        post = datamodel.BoardPost(text=self.request.get('text'))
        
        if(self.request.get('ckey')):
            # Root Post. Place directly on wall.
            post.course = db.get(db.Key(self.request.get('ckey')))
        elif(self.request.get('comment_of')):
            # Comment of Root Post. Place under given Root Post.
            post.comment_of = db.get(db.Key(self.request.get('comment_of')))
        else:
            # post is invalid and should not be retained
            raise InvalidPost('Post was missing root.')
        
        post.put()
        
        self.forward()
